#!/usr/bin/env python3
# coding=utf-8
import time
import requests
import json
import os

import smtplib
from email.mime.text import MIMEText
from email.header import Header

log_file_path = '/var/log/supan_web_server/'
_t = time.strftime("%Y-%m", time.localtime())
    
_fail_ip = ''
_server_ips =  [
            ['120.120.120.120','10105']
        ]
"""
通知相关人员
"""
def report_adm( cpu,used,_type ):
    _t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    Header = {'Content-Type': 'application/json'}
    params = {
            "cpu":"%"+str(cpu),
            "used":"%"+str(used),
            "time":_t
     }
    if _type == 'cpu':
        params['type'] = "运行缓慢"
        _type = 'Cpu:%'+str(cpu)+',Used:%'+str(used)+', Time:'+_t
    else:
        params['type'] = "已Down机"
    send_mail(_type)
    #以下如果有短信接口什么的，可以也能过post请求短信接口等通知IT运维
    #requests.post(data=json.dumps(params).encode('UTF-8'),headers=Header,url="")

"""
发送邮件
"""
def send_mail( _type ):
    if _type is 'down':
        _msg = '服务器Down机'
    else:
        _msg = _type
    mail_host="smtp.163.com"  #设置服务器
    mail_user="xxxxxx@163.com"    #用户名
    mail_pass="xxxxx"   #口令 
    receivers = ['xxxxx@qq.com']  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱
    message = MIMEText(_msg+'，机器['+_fail_ip+']', 'plain', 'utf-8')
    message['From'] = 'xxxxxx<'+mail_user+'>'
    message['To'] =  'IT运维<xxxxx@qq.com>'
    subject = '服务器Down机'
    message['Subject'] = Header(subject, 'utf-8')
    
    try:
        smtpObj = smtplib.SMTP() 
        smtpObj.connect(mail_host, 25)    # 25 为 SMTP 端口号
        smtpObj.login(mail_user,mail_pass)  
        smtpObj.sendmail(mail_user, receivers, message.as_string())
        print('send success')
    except smtplib.SMTPException as e:
        file_name = 'error_' + _t + '.log'
        with open(log_file_path+file_name,'a') as f:
            f.write('[' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '] send mail fail!'+ "\n"+e)


"""

请求服务器，判断是否down机
"""
def _get( url, port ):
    _tt = '[' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '][IP:'+url+':'+port+']'
    _fail_ip = url
    if not os.path.isdir(log_file_path):
        os.makedirs(log_file_path)
    try:
        r = requests.get("http://"+url+":"+port,timeout=60)
        if r.status_code != 200:
            _msg = 'request fail'
            file_name = 'error_' + _t + '.log'
            report_adm(0,0,'down')
        else:
            _b = r.text
            cpu = json.loads(_b).get('cpu')
            mem = json.loads(_b).get('mem')
            free = int(json.loads(_b).get('free'))
            used = int(json.loads(_b).get('used'))
            file_name = "info_" + _t + '.log'
            _msg = 'Cpu:%'+str(cpu)+' Men:'+str(mem)+'GiB Used:%'+str(used)
            if cpu > 8 or used > 80:
                report_adm(cpu,used,'cpu')
    except requests.exceptions.RequestException as e:
        file_name = 'error_' + _t + '.log'
        _msg = 'request timeout!'
        report_adm(0,0,'down')
    finally:
        with open(log_file_path+file_name,'a') as f:
            f.write(_tt+_msg+"\n")

"""
用shell循环此script
"""
if __name__ == '__main__':
    for i in _server_ips:
        _get(i[0],i[1])
